/* pages/review/add/add.js */
const app = getApp();
import Toast from '@vant/weapp/toast/toast';

Page({
    data: {
        orderId: null,
        productTitle: '',
        productImage: '',
        productDesc: '', // Optional: if passed from orders page

        rating: 0, // 初始评分，0表示未评分，或默认为5
        comment: '',
        commentError: '',

        submitting: false,
    },

    onLoad(options) {
        if (!options.orderId) {
            Toast.fail('订单ID缺失');
            wx.navigateBack();
            return;
        }
        this.setData({
            orderId: options.orderId,
            productTitle: options.productTitle || '商品信息',
            productImage: options.productImage || '',
            productDesc: options.productDesc || '', // Optional
        });
    },

    onRatingChange(event) {
        this.setData({
            rating: event.detail,
        });
    },

    onCommentChange(event) {
        this.setData({
            comment: event.detail,
            commentError: '' // Clear error on change
        });
    },

    validateForm() {
        if (this.data.rating === 0) {
            Toast.fail('请给商品评分');
            return false;
        }
        if (!this.data.comment.trim()) {
            this.setData({ commentError: '评价内容不能为空' });
            Toast.fail('评价内容不能为空');
            return false;
        }
        if (this.data.comment.trim().length < 5) {
            this.setData({ commentError: '评价内容至少需要5个字' });
            Toast.fail('评价内容至少需要5个字');
            return false;
        }
        return true;
    },

    async submitReview() {
        if (!this.validateForm() || this.data.submitting) {
            return;
        }

        this.setData({ submitting: true });

        try {
            const res = await new Promise((resolve, reject) => {
                wx.request({
                    url: `${app.globalData.baseUrl}/api/orders/${this.data.orderId}/review`,
                    method: 'POST',
                    header: {
                        'Authorization': 'Bearer ' + wx.getStorageSync('token'), // Assuming token is stored
                        'content-type': 'application/json'
                    },
                    data: {
                        rating: this.data.rating,
                        comment: this.data.comment.trim(),
                    },
                    success: (response) => {
                        resolve(response);
                    },
                    fail: (error) => {
                        reject(error);
                    },
                });
            });

            if (res.statusCode === 200 && res.data.success) {
                Toast.success(res.data.message || '评价成功');
                // 通知订单列表刷新 (重要)
                const pages = getCurrentPages();
                const prevPage = pages[pages.length - 2]; // 订单列表页
                if (prevPage && typeof prevPage.refreshOrderList === 'function') {
                    prevPage.refreshOrderList(); // 调用订单列表页的刷新方法
                } else if (prevPage && typeof prevPage.onPullDownRefresh === 'function') {
                    // 备选方案：如果订单列表页有标准的下拉刷新，可以调用它
                    // 或者直接setData一个标记，让onShow去处理
                    prevPage.setData({
                        needsRefresh: true
                    });
                }

                setTimeout(() => {
                    wx.navigateBack();
                }, 1500);
            } else {
                throw new Error(res.data.message || `评价失败 (${res.statusCode})`);
            }
        } catch (err) {
            console.error('Submit review error:', err);
            Toast.fail(err.message || '评价提交失败，请稍后再试');
        } finally {
            this.setData({ submitting: false });
        }
    },
}); 